
package com.gitee.jmash.rbac.service;

import com.gitee.jmash.core.orm.cdi.JpaTenantService;
import com.gitee.jmash.core.transaction.JakartaTransaction;
import com.gitee.jmash.rbac.entity.UserLogEntity;
import com.gitee.jmash.rbac.entity.UserLogEntity.UserLogPk;
import com.gitee.jmash.rbac.mapper.UserLogMapper;
import com.gitee.jmash.rbac.model.UserLogCreateReq;
import jakarta.enterprise.inject.Typed;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.transaction.Transactional;
import jakarta.transaction.Transactional.TxType;
import jakarta.validation.executable.ValidateOnExecution;
import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * 安全日志 rbac_user_log写服务.
 *
 * @author <a href="mailto:service@crenjoy.com">crenjoy</a>
 */
@Typed(UserLogWrite.class)
@Transactional(TxType.REQUIRED)
@JpaTenantService
@ValidateOnExecution
public class UserLogWriteBean extends UserLogReadBean implements UserLogWrite, JakartaTransaction {


  @Override
  @PersistenceContext(unitName = "WriteRbac")
  public void setEntityManager(EntityManager entityManager) {
    this.tem.setEntityManager(entityManager, true);
  }

  @Override
  public UserLogEntity insert(UserLogCreateReq logReq) {
    UserLogEntity userLogEntity = UserLogMapper.INSTANCE.create(logReq);
    userLogEntity.setCreateTime(LocalDateTime.now());
    userLogEntity.setPartition(LocalDate.now().getMonthValue());
    userLogDao.persist(userLogEntity);
    return userLogEntity;
  }

  @Override
  public UserLogEntity delete(UserLogPk entityId) {
    UserLogEntity entity = userLogDao.removeById(entityId);
    return entity;
  }

  @Override
  public Integer batchDelete(int number) {
    LocalDateTime dateTime = LocalDateTime.now().minusYears(number);
    Integer result = userLogDao.batchDelete(dateTime);
    return result;
  }

}
